<?php

namespace addons\facrm\library\extend\easywechat;

use EasyWeChat\Kernel\Support;

/**
 * 针对 easywechat4.0X的 一些扩展
 * Class SupportExtend
 * @package addons\facrm\library\extend\easywechat
 */
class SupportExtend
{
    protected $app = null;

    public function __construct($app)
    {
        $this->app=$app;
    }


    /**
     * Get agent config json for jsapi.
     * @param array $jsApiList
     * @param int|string $agentId
     * @param bool $debug
     * @param bool $beta
     * @param bool $json
     * @param array $openTagList
     * @param string|null $url
     * @return array|string
     */
    public function buildAgentConfig(
        array $jsApiList,
        $agentId,
        bool $debug = false,
        bool $beta = false,
        bool $json = true,
        array $openTagList = [],
        string $url = null
    )
    {
        $config = array_merge(compact('debug', 'beta', 'jsApiList', 'openTagList'), $this->agentConfigSignature($agentId, $url));

        return $json ? json_encode($config) : $config;
    }

    /**
     * @param int|string $agentId
     * @param string|null $url
     * @param string|null $nonce
     * @param null $timestamp
     *
     * @return array
     *
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function agentConfigSignature($agentId, string $url = null, string $nonce = null, $timestamp = null): array
    {
        $url = $url ?: $this->app->jssdk->getUrl();
        $nonce = $nonce ?: Support\Str::quickRandom(10);
        $timestamp = $timestamp ?: time();
        return [
            'corpid' => $this->app->config['corp_id'],
            'agentid' => $agentId,
            'nonceStr' => $nonce,
            'timestamp' => $timestamp,
            'url' => $url,
            'signature' => $this->app->jssdk->getTicketSignature($this->app->jssdk->getAgentTicket($agentId)['ticket'], $nonce, $timestamp, $url),
        ];
    }

}